<template>
	<view class="app">
		<!-- 页面内容开始 -->
		<!-- 图片轮播 + 视频轮播（视频默认自动静音播放）  750*750-->
		<u-swiper-plus
			:list="bannerListCom" :height="750" :radius="0" indicator-mode="dot"
			:indicator="bannerIndicatorCom" :video-autoplay="true" :video-muted="true"
			indicator-active-color="rgb(168, 168, 168)"
			indicator-inactive-color="rgba(168, 168, 168, 0.35)"
		></u-swiper-plus>
		<!-- 价格 ¥198.00 - ¥598.00 划线价 ¥398.00 - ¥998.00-->
		<view class="price-box">
			<view class="flex-box">
				<!-- 销售价 -->
				<view class="sale-price" :style="'font-size: '+(salePriceSizeFn(salePriceCom.length))+'rpx;'">
					<text class="unit" v-if="salePriceCom">¥</text>
					<text>{{ salePriceCom || '请稍等...' }}</text>
				</view>
				<view class="collection" @click="collectGoods">
					<view class="vk-contents" v-if="isCollect">
						<u-icon name="vk-icon-likefill" size="40" color="var(--main)"></u-icon>
						<text class="text">收藏</text>
					</view>
					<view class="vk-contents" v-else>
						<u-icon name="vk-icon-like" size="40"></u-icon>
						<text class="text">收藏</text>
					</view>
				</view>
				<view class="goods-share" @click="shareCard()">
					<button class="share-button" open-type="share" :plain="true">
						<view><u-icon name="vk-mall-icon-fenxiang1" size="40"></u-icon></view>
						<view class="goods-share-text">分享</view>
					</button>
				</view>
			</view>
			<!-- 划线价 -->
			<view class="market-price" v-if="marketPriceCom">{{ marketPriceCom }}</view>
		</view>

		<!-- 商品名称 , 最多显示2行 右侧有分享按钮-->
		<view class="goods-name-box">
			<view class="goods-name u-line-2">{{ goods.name }}</view>
		</view>

		<!-- 商品描述,最多显示1行 -->
		<view class="goods-desc">{{ goods.goods_desc }}</view>
		<view v-if="giveIntegralCom">
			<u-notice-bar mode="vertical" :list="[giveIntegralCom]" :volume-icon="false" type="warning" :close-icon="false" font-size="24"></u-notice-bar>
		</view>
		<!-- 标签,最多显示1行 -->
		<view class="goods-tags" v-if="goods.goods_tags && goods.goods_tags.length > 0">
			<text class="goods-tag" v-for="(tag,index) in goods.goods_tags" :key="index">
				{{ tag }}
			</text>
		</view>
		<view class="goods-validity-time" v-if="goods.type === 1">
			<text class="goods-validity-time-title">说明</text>
			<text>{{ vk.myfn.goods.getValidityTimeStr(goods) }}</text>
		</view>

		<!-- 库存剩余显示 -->
		<!-- sku规格选择 -->
		<!-- 商品评价数量显示 -->
		<u-cell-group class="cell-group">
			<u-cell-item title="服务" :arrow="false" hover-class="none" v-if="goods.goods_services && goods.goods_services.length > 0">
				<view class="vk-contents" v-for="(tag,index) in goods.goods_services" :key="index">
					<u-icon name="checkmark-circle" color="#fa3534"></u-icon>
					<text class="goods-service"> {{ tag }} </text>
				</view>
			</u-cell-item>
			<u-cell-item title="浏览量" :value="vk.pubfn.numStr(goods.view_count)" :arrow="false" hover-class="none"></u-cell-item>
			<u-cell-item title="库存剩余" :arrow="false" hover-class="none">
				<text>{{ stockCom }} 件</text>
			</u-cell-item>
			<u-cell-item title="已选规格" :value="skuNameCom" @click="buyGoods(1)"></u-cell-item>
			<u-cell-item title="商品评价" @click="toComment">
				<text v-if="goods.comment_count>0">共 {{ goods.comment_count }} 条评价</text>
				<text v-else>暂无评价</text>
			</u-cell-item>
		</u-cell-group>

		<!-- 商品详情页图片展示 -->
		<view class="goods-detail-images">
			<view class="goods-detail-images-title"> 商品详情 </view>
			<view class="vk-contents" v-if="!goods.goods_detail_mode">
				<u-image :src="item" mode="widthFix" v-for="(item,index) in goods.goods_detail_imgs" :key="index" lazy-load width="100%"/>
			</view>
			<view class="vk-contents" v-else-if="goods.goods_detail_body">
				<u-parse :html="goods.goods_detail_body" :selectable="true" :lazy-load="true" :preview="false"></u-parse>
			</view>
		</view>
		<!-- 底部安全区域 -->
		<view class="safe-area-inset-bottom"></view>

		<!-- 底部按钮区 客服 首页 购物车 加入购物车 立即购买 -->
		<view class="navigation">
			<view class="navigation-main">
				<view class="navigation-main-left">
					<view class="icon-btn" @click="toHome">
						<view><u-icon name="vk-mall-icon-dianpu" size="40"></u-icon></view>
						<view>首页</view>
					</view>

					<!-- 微信小程序客服方案 -->
					<view class="icon-btn" v-if="mpWeixinOnlineServiceCom">
						<button
							class="contact"
							:plain="true"
							open-type="contact"
							:send-message-title="goods.name"
							:send-message-path="'/pages/goods/goods-detail?_id='+goods._id"
							:send-message-img="goods.goods_thumb"
							:show-message-card="true"
							session-from="goods-detail"
							@click="toCustomerService"
						>
							<view><u-icon name="vk-mall-icon-kehu" size="40"></u-icon></view>
							<view>客服</view>
						</button>
					</view>
					<!-- 通用客服方案，直接加微信 -->
					<view class="icon-btn" @click="toServiceCenter" v-else>
						<view><u-icon name="vk-mall-icon-kehu" size="40"></u-icon></view>
						<view>客服</view>
					</view>
					<view class="icon-btn" @click="toCart">
						<view style="position: relative;">
							<u-badge v-if="cartTotalCom > 0" :count="cartTotalCom" :offset="[-10, -10]" ></u-badge>
							<u-icon name="vk-mall-icon-gouwuche" size="40"></u-icon>
						</view>
						<view>购物车</view>
					</view>
				</view>
				<view class="navigation-main-right" v-if="!complete">
					<view class="navigation-not-sale">loading...</view>
				</view>
				<view class="navigation-main-right" v-else-if="goods.is_on_sale">
					<view class="navigation-cart" @click="buyGoods(2)">{{ goods.type === 0 ? '加入购物车' : '立即购买' }}</view>
					<view class="navigation-buy"><text class="buy-btn" @click="buyGoods(3)">买</text></view>
				</view>
				<view class="navigation-main-right" v-else>
					<view class="navigation-not-sale">该商品已下架</view>
				</view>
			</view>
			<view class="navigation-inset-bottom"></view>
		</view>

		<!-- sku弹窗组件 -->
		<vk-mall-goods-sku-popup v-model="skuPopup.show" :goods-info="goods" :mode="skuPopup.mode"/>
		
		<!-- #ifdef H5 -->
		<vk-mall-h5-share ref="h5Share"></vk-mall-h5-share>
		<!-- #endif -->

		<!-- 全局公共浮球导航模块 -->
		<vk-data-float-ball :scroll-top="scrollTop"></vk-data-float-ball>
		<vk-data-loading v-model="loading" delayTime="0"></vk-data-loading>
		<!-- 页面内容结束 -->
	</view>
</template>

<script>
var vk = uni.vk; // vk依赖
export default {
	data() {
		// 页面数据变量
		return {
			// 商品信息
			goods: {
				name:"载入中...",
				sku_list: [],
				goods_thumb:""
			},
			isCollect: false,
			// 滚动条高度
			scrollTop: 0,
			// sku弹窗组件
			skuPopup:{
				show:false,
				mode:1
			},
			complete:false,
			loading: false
		};
	},
	onPageScroll(e) {
		this.scrollTop = e.scrollTop;
	},
	// 监听 - 页面每次【加载时】执行(如：前进)
	onLoad(options = {}) {
		vk = uni.vk;
		this.options = options;
		this.init(options);
	},
	// 监听 - 页面【首次渲染完成时】执行。注意如果渲染速度快，会在页面进入动画完成前触发
	onReady() {},
	// 监听 - 页面每次【显示时】执行(如：前进和返回) (页面每次出现在屏幕上都触发，包括从下级页面点返回露出当前页面)
	onShow() {},
	// 监听 - 页面每次【隐藏时】执行(如：返回)
	onHide() {},
	// 监听 - 点击右上角转发时 https://uniapp.dcloud.io/api/plugins/share.html#onshareappmessage
	onShareAppMessage(options) {
		return vk.myfn.onShareAppMessage({
			options,
			title: this.goods.name,
			imageUrl: this.goods.goods_thumb
		});
	},
	// 函数
	methods: {
		// 页面数据初始化函数
		init(options) {
			let that = this;
			let { _id } = options;
			// 尝试从上一页中获取商品数据渲染（实时响应数据，增加用户体验，用户看到的效果就是商品数据实时渲染不卡顿）
			const eventChannel = that.getOpenerEventChannel();
			// 监听data事件，获取上一页面通过eventChannel.emit传送到当前页面的数据
			if (eventChannel.on) {
				eventChannel.on('data', (data) => {
					that.setGoods(data);
				});
			}
			// 不管能否从上一页中获取到商品数据，依然会请求一次后端，拉去到此商品的最新数据。
			vk.callFunction({
				url: 'client/pub.getGoodsInfo',
				loading:true,
				data:{
					_id
				},
				success:(data) => {
					that.setGoods(data.info);
					that.isCollect = data.isCollect;
					// 添加商品访问记录
					let keyName = "user-browsing";
					let userBrowsingObj = vk.getStorageSync(keyName) || {};
					let browse_num = vk.pubfn.getData(userBrowsingObj, `${data.info._id}.browse_num`,0);
					userBrowsingObj[data.info._id] = {
						data: data.info, // 商品信息
						browse_time: Date.now(), // 最新浏览时间
						browse_num: ++browse_num, // 浏览次数
					}
					vk.setStorageSync(keyName, userBrowsingObj);
				}
			});
		},
		setGoods(goods) {
			let that = this;
			that.goods = goods;
			that.complete = true;
			uni.setNavigationBarTitle({
				title: goods.name
			});
		},
		// 返回首页
		toHome(){
			vk.navigateToHome();
		},
		// 前往购物车页面
		toCart(){
			vk.navigateTo('./goods-cart');
		},
		// 前往客服服务
		toCustomerService(){
			// #ifndef MP
			vk.toast("请在微信小程序中打开!");
			// #endif
		},
		// 前往商品评价页面
		toComment(){
			let that = this;
			vk.navigateTo(`./goods-comment?_id=${that.goods._id}`);
		},
		salePriceSizeFn(length){
			let size = 60 - length;
			if (size<24) size = 24;
			if (size>46) size = 46;
			return size;
		},
		buyGoods(mode){
			let that = this;
			if (that.goods && that.goods._id) {
				that.skuPopup.show = true;
				that.skuPopup.mode = mode;
			}
		},
		// 收藏商品
		collectGoods(){
			let that = this;
			// 如果未收藏,则添加收藏,已收藏,则删除收藏
			vk.callFunction({
				url: 'client/user.collectGoods',
				loading: true,
				data: {
					goods_id: that.goods._id,
					type: that.isCollect ? 2 : 1
				},
				success: (data) => {
					vk.toast(data.msg);
					that.isCollect = data.isCollect;
				}
			});
		},
		toServiceCenter(){
			vk.navigateTo('/pages/service-center/service-center');
		},
		// 卡片形式分享
		shareCard(){
			// #ifdef APP-PLUS
			vk.myfn.appShare({
				provider: "weixin",
				scene: "WXSceneSession",
				type: 5, // 0:h5 5:小程序
				title: this.goods.name,
				imageUrl:this.goods.goods_thumb,
				pagePath: `/pages/goods/goods-detail?_id=${this.goods._id}`
			});
			// #endif
			// #ifdef H5
			this.$refs.h5Share.show();
			// #endif
		},
	},
	// 监听器
	watch: {},
	// 计算属性
	computed: {
		// 购物车商品总数量计算
		cartTotalCom(){
			return uni.vk.myfn.cart.getTotal();
		},
		// 销售价计算
		salePriceCom(){
			let that = this;
			let { goods={} } = that;
			let str = "";
			if (goods.sku_list && goods.sku_list.length > 0) {
				let min = Number.MAX_VALUE;
				let max = 0;
				goods.sku_list.map((item, index) => {
					if (item.price < min) {
						min = item.price;
					}
					if (item.price > max) {
						max = item.price;
					}
				});
				if (min === max) {
					str = `${vk.pubfn.priceFilter(min)}`
				} else {
					str = `${vk.pubfn.priceFilter(min)} - ${vk.pubfn.priceFilter(max)}`;
				}
			}
			return str;
		},
		// 市场价计算
		marketPriceCom(){
			let that = this;
			let { goods={} } = that;
			let str = "";
			if (goods.sku_list && goods.sku_list.length > 0) {
				let min = Number.MAX_VALUE;
				let max = 0;
				goods.sku_list.map((item, index) => {
					if (item.market_price < min) {
						min = item.market_price;
					}
					if (item.market_price > max) {
						max = item.market_price;
					}
				});
				if (max > 0){
					if (min === max || min == 0) {
						str = `¥${vk.pubfn.priceFilter(max)}`
					} else {
						str = `¥${vk.pubfn.priceFilter(min)} - ${vk.pubfn.priceFilter(max)}`;
					}
				}
			}
			return str;
		},
		// 库存计算
		stockCom(){
			let that = this;
			let { goods={} } = that;
			let num = "-";
			if (goods.sku_list && goods.sku_list.length > 0) {
				num = 0;
				goods.sku_list.map((item, index) => {
					num += item.stock;
				});
			}
			return num;
		},
		skuNameCom(){
			let str = "请选择规格";
			let that = this;
			let { goods={} } = that;
			if (goods.sku_list && goods.sku_list.length == 1) {
				str = `已选 ${goods.sku_list[0].sku_name}`;
			}
			return str;
		},
		giveIntegralCom(){
			let str = "";
			let that = this;
			let { goods={} } = that;
			let {
				integral_rule = {},
			} = goods;
			let {
				is_calc,
				is_fixed_calc,
				proportion_value,
				fixed_value,
				is_level_k,
			} = integral_rule;
			if (is_calc) {
				let str2 = is_level_k ? "" : "（不受VIP积分倍率影响）";
				if (is_fixed_calc) {
					// 固定
					str = `现在下单奖励 ${fixed_value} 个积分${str2}`;
				} else {
					// 百分比
					str = `现在下单奖励付款金额 * ${vk.pubfn.percentageFilter(proportion_value)}的积分${str2}`
				}
			}
			return str;
		},
		mpWeixinOnlineServiceCom(){
			// #ifdef MP-WEIXIN
			let online_service = uni.vk.getVuex('$user.mchInfo.mp_weixin.online_service');
			return online_service;
			// #endif
			// #ifndef MP-WEIXIN
			return false;
			// #endif
		},
		bannerListCom(){
			let { goods={} } = this;
			let { goods_banner_imgs=[], goods_banner_videos=[] } = goods;
			let imgs = goods_banner_imgs.map((item, index) => {
				return item;
			});
			let videos = goods_banner_videos.map((item, index) => {
				return item;
			});
			return videos.concat(imgs);
		},
		// 只有轮播图数量大于1时才需要显示面板指示器
		bannerIndicatorCom(){
			let { bannerListCom=[] } = this;
			return bannerListCom.length > 1 ? true : false;
		}
	}
};
</script>
<style lang="scss" scoped>
	.app{
		background-color: #f8f8f8;
		min-height: calc(100vh - var(--window-bottom));
	}
	.price-box{
		background-color: #ffffff;
		padding: 30rpx 30rpx 10rpx 30rpx;
		min-height: 120rpx;
		.flex-box{
			display: flex;
			align-items: center;
			.sale-price{
				color: var(--main);
				font-size: 46rpx;
				font-weight: bold;
				flex:1;
				.unit{
					font-size: 28rpx;
					margin-right: 8rpx;
				}
			}
			.collection{
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				.text{
					font-size: 24rpx;
				}
			}
		}
		.market-price{
			color: #909399;
			text-decoration:line-through;
			font-size: 24rpx;
			margin-left: 10rpx;
		}
	}


	.goods-name-box{
		display: flex;
		background-color: #ffffff;
		align-items: center;
		padding: 0rpx 30rpx 10rpx 30rpx;
		.goods-name{
			flex:1;
			font-weight: bold;
			font-size: 30rpx;
		}
	}

	.goods-desc{
		background-color: #ffffff;
		color: #909399;
		padding: 0 30rpx 30rpx 30rpx;
		font-size: 26rpx;
	}
	.goods-tags{
		background-color: #ffffff;
		color: #5e6064;
		padding: 0 30rpx 30rpx 30rpx;
		font-size: 24rpx;
		.goods-tag::before{
			content: "•";
			margin-right: 5px;
		}
		.goods-tag +.goods-tag{
			margin-left: 10rpx;
		}
	}
	.goods-validity-time{
		margin-top: 10rpx;
		padding: 10rpx 30rpx;
		background-color: #ffffff;
		.goods-validity-time-title{
			font-weight: bold;
			margin-right: 20rpx;
		}
	}

	.goods-service{
		margin: 0 6rpx;
	}

	.cell-group{
		margin-top: 10rpx;
		background-color: #ffffff;
	}
	.goods-detail-images{
		width: 100%;
		margin-top: 10rpx;
		.goods-detail-images-title{
			background-color: #ffffff;
			padding: 20rpx;
			font-weight: bold;
			font-size: 34rpx;
		}
		image{
			width: 100%;
			display: block;
		}
		::v-deep .vk-data-editor-image{
			width: 100%;
			display: block;
		}
	}
	/* 底部按钮区 */
	.navigation {
		position: fixed;
		bottom: 0;
		border-top: solid 2rpx #f2f2f2;
		background-color: #ffffff;
		width: 100%;
		z-index: 99;
		.navigation-main{
			display: flex;
			position: relative;
			padding: 30rpx 20rpx;
			.navigation-main-left{
				flex: 4;
				display: flex;
				justify-content: space-around;
				align-items: center;
				font-size: 24rpx;
				.icon-btn{
					text-align: center;
				}
				.contact{
					border: 0;
					line-height: initial;
					font-size: 24rpx;
					padding: 0;
					margin: 0;
				}
			}
			.navigation-main-right{
				flex: 5;
				display: flex;
				align-items: center;
				.navigation-not-sale{
					background-color: rgba(0,0,0,0.1);
					color:#ffffff;
					padding: 20rpx 50rpx;
					border-radius: 20rpx;
					font-size: 30rpx;
					font-weight: bold;
					margin-left: 20rpx;
					flex: 1;
					text-align: center;
				}
				.navigation-cart{
					background-color: #f7f7f7;
					color: var(--main);
					padding: 20rpx 50rpx;
					border-radius: 20rpx 0 0 20rpx;
					font-size: 30rpx;
					font-weight: bold;
					margin-left: 20rpx;
				}
				.navigation-cart:active{
					background-color: rgba(0,0,0,0.1);
					color:#ffffff;
				}
				.navigation-buy{
					position: absolute;
					top:-26rpx;
					right: 0;
					z-index: 2;
					width: 180rpx;
					height: 180rpx;
					border-radius: 50%;
					background-color: #FFFFFF;
					border-top: solid 2rpx #f2f2f2;
					border-left: solid 2rpx #FFFFFF;
					border-right: solid 2rpx #FFFFFF;
					color: #FFFFFF;
					display: flex;
					justify-content: center;
					align-items: center;
					font-size: 40rpx;
					font-weight: bold;
					.buy-btn{
						width: 120rpx;
						height: 120rpx;
						border-radius: 50%;
						background-color: var(--main);
						display: flex;
						justify-content: center;
						align-items: center;
					}
					.buy-btn:active{
						filter: grayscale(50%);
					}
				}
			}
		}
		.navigation-inset-bottom{
			height: 0;
			height: constant(safe-area-inset-bottom);
			height: env(safe-area-inset-bottom);
			display: block;
			width: 100%;
		}
	}

	/* 底部安全区域 */
	.safe-area-inset-bottom{
		height: calc(140rpx);
		height: calc(140rpx + constant(safe-area-inset-bottom));
		height: calc(140rpx + env(safe-area-inset-bottom));
		display: block;
	}

	.goods-share{
		margin-left: 20rpx;
		.goods-share-text{
			font-size: 24rpx;
		}
		.share-button{
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			padding: 0;
			margin: 0;
			border: 0;
			line-height: initial;
			color: #303133;
			font-size: 24rpx;
		}
	}

</style>
